// packageI/AdBright/AdBrightWx/AdBrightWx.js
const app = getApp();
import logs from "../../../utils/logs"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    integral: '',
    placementId: '',
    mini_form_id: '', //小程序流量主广告单元ID
    level_credit: 0, //当前等级观看可获取积分
    level_data: [],
    adv_list: [],
    member: {},
    level_index: 0,
    redirectToUrl: '',
    Partner: false,
    pid: '',
    //防止多次点击
    isclick:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const value = wx.getStorageSync('integral');
    if (value) {
      this.setData({
        integral: value
      });
    }
    if (options.wxad) {
      this.setData({
        mini_form_id: options.wxad
      })
    }
    this.data.redirectToUrl = '/packageI/AdBright/AdBrightIndex/AdBrightIndex';
    this.init();
  },
  async init() {
    let that = this;
    let rewardedVideoAd = null
    if (wx.createRewardedVideoAd) {
      // wxad=adunit-ae73b2ecdd0774eb
      rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: this.data.mini_form_id
      })
      rewardedVideoAd.onLoad(() => {
        rewardedVideoAd.show()
        console.log('onLoad event emit')
      })
      rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      })
      rewardedVideoAd.onClose((res) => {
        rewardedVideoAd.destroy()
        if (res.isEnded) {
          console.log("流量主广告达到奖励条件",res)
          logs.info('------------流量主广告达到奖励条件--------------',res)
          that.getReward(true)
          return
        } else {
          wx.reLaunch({
            url: this.data.redirectToUrl
          })
          return
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getReward(redirectTo) {
    if(this.data.isclick){
      return
    }
    this.data.isclick = true;
    let that = this;
    let urlStr = app.getNetAddresss("plugin.flyers-advertise.frontend.reward.miniReward");
    app._postNetWork({
      url: urlStr,
      success: (resdata) => {
        let res = resdata.data;
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false,
          success:(res)=> {
            if (redirectTo) {
              wx.reLaunch({
                url: that.data.redirectToUrl,
                success:(res)=>{
                  this.data.isclick = false
                }
              })
            }
          }
        })
      },
      fail: (res) => {
        console.log(res);
      },
    });

  },
})